<?php

namespace App\Models\Notice;

use App\Models\BaseModel;
use App\Helpers\Code;
use DB;
use App\Models\Notice\NoticeRecord;
use App\Models\Account\User;
use Illuminate\Support\Facades\Auth;

class SystemNotice extends BaseModel
{

    protected $table = 'system_notices';
    protected $fillable = ['title', 'content', 'receiver', 'created_by', 'type', 'data_scope'];
    public $params = ['title'];
    public $sorters = ['title', 'created_at'];

    public function user()
    {
        return $this->belongsToMany('App\Models\Account\User', 'notice_records', 'notice_id', 'user_id');
    }

    public function addSystemNotice($data)
    {
        $userArr = User::whereIn('id', $data['receiver'])->get(['id']);
        if (count($userArr) != count($data['receiver'])) {
            return Code::INSIDE_EXIST_DEPENDENCE;
        }

        $data['receiver'] = json_encode($data['receiver']);
        DB::beginTransaction();
        $data['data_scope'] = $this->getDataScope();
        $systemNotice = $this->create($data);
        if ($systemNotice) {
            $insertData = array();
            $insertData['notice_id'] = $systemNotice->id;
            $insertData['created_at'] = date('Y-m-d H:i:s');
            $insertData['updated_at'] = date('Y-m-d H:i:s');
            $insertData['data_scope'] = $this->getDataScope();
            $insertDataArr = array();
            $receiverArr = json_decode($data['receiver'], true);
            foreach ($receiverArr as $uid) {
                $insertData['user_id'] = $uid;
                $insertDataArr[] = $insertData;
            }

            $noticeRecord = new NoticeRecord();
            if ($noticeRecord->insert($insertDataArr)) {
                DB::commit();
                return $systemNotice;
            } else {
                DB::rollBack();
                return Code::INSIDE_ERROR_1;
            }
        }
        return null;
    }

    public function deleteSystemNotice($id)
    {
        $systemNotice = SystemNotice::find($id);
        if ($systemNotice) {
            $result = $systemNotice->delete();
            if ($result) {
                return NoticeRecord::where('notice_id', '=', $id)->delete();
            } else {
                return Code::INSIDE_ERROR_1;
            }
        } else {
            return null;
        }
    }

    public function getSystemNoticeList($limit, $sorter, $search)
    {
        $perPage = $limit > 0 ? $limit : $this->limit;
        $systemNotice = $this->orderBy($sorter[0], $sorter[1]);
        $systemNotice->select(['id', 'title', 'content', 'created_at']);

        foreach ($search as $key => $value) {
            switch ($key) {
                case 'title':
                    $systemNotice->where($key, 'like', '%' . $value . '%');
                    break;
            }
        }
        return $systemNotice->paginate($perPage)->toArray();
    }

    public function getSystemNotice($id)
    {
        $systemNotice = $this->with('user:username')->where('id', '=', $id)->first(['title', 'content', 'id', 'created_by']);
        if ($systemNotice) {
            return $systemNotice->toArray();
        } else {
            return null;
        }
    }

    public function getNoticeListAll()
    {
        $data = [];

        $userId = Auth::id();

        $systemNotices = NoticeRecord::with('notice:id,title')
                ->where('user_id', $userId)
                ->where('is_readed', 0)
                ->orderBy('created_at', 'desc')
                ->take(10)
                ->get(['id', 'notice_id', 'created_at'])
                ->toArray();

        $taskNotices = SmsRecord::with('task:id,title,type')
                ->where('user_id', $userId)
                ->where('is_readed', 0)
                ->orderBy('created_at', 'desc')
                ->take(10)
                ->get(['id', 'task_id', 'content', 'created_at', 'type'])
                ->toArray();

        foreach ($systemNotices as $item) {
            $data[] = ['id' => $item['id'], 'type' => '通知', 'title' => $item['notice']['title'], 'datetime' => $item['created_at'], 'avatar' => asset('/assets/img/notice_1.png')];
        }

        $type = [1 => '工作项分配', 2 => '工作项录入', 3 => '节点审核', '4' => '节点设置'];
        $status = [1 => 'todo', 2 => 'processing', 3 => 'doing', 4 => 'urgent'];

        foreach ($taskNotices as $item) {
            $record = ['id' => $item['id'], 'description' => $item['content'], 'datetime' => $item['created_at']];
            switch ($item['type']) {
                case Code::SMS_TYPE_0:
                    $data[] = array_merge($record, [
                        'type' => '待办',
                        'title' => $item['task']['title'],
                        'extra' => $type[$item['task']['type']],
                        'status' => $status[$item['task']['type']]
                    ]);
                    break;
                case Code::SMS_TYPE_1:
                    $data[] = array_merge($record, [
                        'type' => '消息',
                        'extra' => '咨询提醒',
                        'status' => $status[1],
                    ]);
                    break;
                case Code::SMS_TYPE_2:
                    $data[] = array_merge($record, [
                        'type' => '消息',
                        'extra' => '更新信息',
                        'status' => $status[4],
                    ]);
                    break;
                case Code::SMS_TYPE_3:
                    $data[] = array_merge($record, [
                        'type' => '消息',
                        'extra' => '临床计划',
                        'status' => $status[2],
                    ]);
                    break;
                case Code::SMS_TYPE_4:
                    $data[] = array_merge($record, [
                        'type' => '消息',
                        'extra' => '物流通知',
                        'status' => $status[3],
                    ]);
                    break;
            }
        }

        return $data;
    }

    public function clearNotices($data)
    {
        $userId = Auth::id();

        switch ($data['type']) {
            case 'system':
                $record = NoticeRecord::where('user_id', $userId)->where('is_readed', '!=', 1)->whereIn('id', $data['notice'])->update(['is_readed' => 1]);
                if (!$record) {
                    return null;
                }
                break;
            case 'sms':
                $record = SmsRecord::where('user_id', $userId)->where('type', Code::SMS_TYPE_0)->where('is_readed', '!=', 1)->whereIn('id', $data['notice'])->update(['is_readed' => 1]);
                if (!$record) {
                    return null;
                }
                break;
            case 'message':
                $record = SmsRecord::where('user_id', $userId)->whereIn('type', [Code::SMS_TYPE_1, Code::SMS_TYPE_2, Code::SMS_TYPE_3, Code::SMS_TYPE_4])->where('is_readed', '!=', 1)->whereIn('id', $data['notice'])->update(['is_readed' => 1]);
                if (!$record) {
                    return null;
                }
                break;
        }

        return true;
    }

}
